package com.xw.wuliu;


import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.corey.handler.MyContentHandler;
import com.corey.model.MyLocation;
import com.corey.utils.FileUtils;
import com.corey.utils.HttpDownloader;
import com.corey.utils.LocationUtil;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class SignActivity extends Activity{
	

//	private static final String PREFS_SIGNFLAG = "signFlag";
//	private int signFlag = 0; // 0为已下班 1为已上班
	private LocationUtil locationUtil;
	
	private Button btBack;
	private Button btSignWork;
	private Button btSignUnwork;
	
	private double latitude = 0.0;
	private double longitude = 0.0;
	
	class MyHandler extends Handler{
		public MyHandler(){
			
		}
		public MyHandler(Looper looper){
			super(looper);
		}
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			String strflag="";
			List<String> strs = new ArrayList<String>();
			
			Bundle b = msg.getData();
			int flag = b.getInt("flag");
			if (flag == 1) {
//				System.out.println("Handler--->"+ Thread.currentThread().getId());
				
				String userPaName = b.getString("userPaName");
				String time = b.getString("time");
//				System.out.println("userPsname="+userPaName+"&lo="+longitude+"&la="+latitude+"&workOnCheckTime="+time);
				HttpDownloader hd = new HttpDownloader();
				String resultStr = hd.download(FileUtils.urlStr+"WorkOncheck?userPsname="+userPaName+"&lo="+longitude+"&la="+latitude+"&workOnCheckTime="+time);
//				System.out.println("URL:"+ FileUtils.urlStr+"WorkOncheck?userPsname="+userPaName+"&lo="+longitude+"&la="+latitude+"&workOnCheckTime="+time);
				System.out.println("result:"+resultStr);
				
				
				try{
					//����һ��SAXParserFactory
					SAXParserFactory factory = SAXParserFactory.newInstance();
					XMLReader reader = factory.newSAXParser().getXMLReader();
					//ΪXMLReader�������ݴ�����
					MyContentHandler myContentHandler = new MyContentHandler(strs);
					reader.setContentHandler(myContentHandler);
					//��ʼ�����ļ�
					reader.parse(new InputSource(new StringReader(resultStr)));
					for (Iterator iterator = strs.iterator(); iterator.hasNext();) {
						strflag = (String) iterator.next();
//						System.out.println("Str@@@@"+ string);
					}
				}
				catch(Exception e){
					e.printStackTrace();
				}
					
				if("WorkOncheck_success".equals(strflag)){
					Toast.makeText(getApplicationContext(), "签到成功", 1).show();
				}else if("WorkOncheck_fail".equals(strflag)){
					Toast.makeText(getApplicationContext(), "签到失败", 1).show();
				}else{
					System.out.println("handler_error");
				}
				
			}else{
				
			}
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.signin);
		

//		System.out.println("signFlag1:"+signFlag);
		findViews();
		setBtVis();
		setListensers();
//		System.out.println("signFlag2:"+signFlag);
	}
	
	private void findViews(){
		btBack = (Button) findViewById(R.id.btback);
		btSignWork = (Button) findViewById(R.id.bt_signWork);
		btSignUnwork = (Button) findViewById(R.id.bt_signUnwork);
	}
	
	private void setBtVis(){
//		loadSignFlag();
		boolean signFlag = isServiceRunning("com.xw.service.LocationTrackerSvc");
		if(signFlag){
			btSignUnwork.setVisibility(View.VISIBLE);
			btSignWork.setVisibility(View.INVISIBLE);
		}else {
			btSignUnwork.setVisibility(View.INVISIBLE);
			btSignWork.setVisibility(View.VISIBLE);
		}
	}
	
	private void setListensers(){
		
		btBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				SignActivity.this.finish();
			}
		});
		
		btSignWork.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				btSignWork.setVisibility(View.INVISIBLE);
				btSignUnwork.setVisibility(View.VISIBLE);
				
//				signFlag = 1;
//				saveSignFlag();
				
//				String userPaNa = getUser();
				getLocation();
//				String timeStr = getTime();
				downLoadInfo(getUser(),getTime(),latitude,longitude);
				startLocBackSvc();
			}
		});
		
		btSignUnwork.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				btSignUnwork.setVisibility(View.INVISIBLE);
				btSignWork.setVisibility(View.VISIBLE);
				
//				signFlag = 0;
//				saveSignFlag();
				
//				String userPaNa = getUser();
				getLocation();
//				String timeStr = getTime();
				downLoadInfo(getUser(),getTime(),latitude,longitude);
				stopLocBackService();
			}
		});
	}

	// 获取上班签到的信息
	private String getUser(){
		// 得到用户名
		String userPaName = this.getIntent().getExtras().getString("userPaName");
		System.out.println("username:" + userPaName);
		return userPaName;
	}

	// 得到当前经纬度
	private void getLocation() {
		// 获取经纬度
		locationUtil = new LocationUtil(this);
		if(locationUtil.isEnbled() == true) {
			locationUtil.exec();
			MyLocation location = locationUtil.getMyLocation();
//			txt.setText("当前坐标是：\n经度:" + location.getLatitude() + "\n纬度:" + location.getLongitude());
			latitude = location.getLatitude();
			longitude = location.getLongitude();
		}else{
			Toast.makeText(SignActivity.this, "无法获取当前位置", Toast.LENGTH_LONG).show();
		}
		System.out.println("latitude:"+latitude + "longitude:" + longitude);
	}
	
	//获取当前时间
	private String getTime() {
		// 获取当前时间
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss");
		Date curDate = new Date(System.currentTimeMillis());
		String timeStr = formatter.format(curDate);
		System.out.println("timeStr:" + timeStr);
		return timeStr;
	}
	
	/**
	 * @function 开启后台位置上传服务
	 * 
	 */
	public void startLocBackSvc()
	{
		
		Intent i = new Intent();
		i.setAction("com.xw.locationsvc");
		this.startService(i);
		
	}
	
	/**
	 *  @function 停止后台位置上传服务
	 * 
	 * 
	 */
	public void stopLocBackService()
	{
		Intent i = new Intent();
		i.setAction("com.xw.locationsvc");
		this.stopService(i);
	}
	
	
//	private void saveSignFlag(){
//		//载入配置文件
//		SharedPreferences sp = getSharedPreferences(PREFS_SIGNFLAG, 0);
//		//写入配置文件
//		Editor spEd = sp.edit();
//		spEd.putInt("signFlag", signFlag);
//		spEd.commit();
//	}
//	
//	private void loadSignFlag(){
//		SharedPreferences sp = getSharedPreferences(PREFS_SIGNFLAG, 0);
//		signFlag = sp.getInt("signFlag", 0);
//	}
	
	private void downLoadInfo(String userPaName,String time,double latitude,double longitude){
		
//		System.out.println("act--->"+ Thread.currentThread().getId());
		HandlerThread handlerThread = new HandlerThread("handler_thread");
		handlerThread.start();
		MyHandler myHandler = new MyHandler(handlerThread.getLooper());
		Message msg = myHandler.obtainMessage();
		Bundle b = new Bundle();
		b.putInt("flag", 1);
		b.putString("userPaName", userPaName);
		b.putString("time", time);
		b.putDouble("la", latitude);
		b.putDouble("lo", longitude);
		msg.setData(b);
		msg.sendToTarget();
		
	}
	
	/**
	 * 
	 * 判断sevice是否运行着
	 * 
	 * @param serviceName
	 * @return
	 */

	public boolean isServiceRunning(String serviceName) {
		
		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningServiceInfo> infos = manager.getRunningServices(30);
		for (RunningServiceInfo info : infos) {			
			System.out.println("serName:" + info.service.getClassName());
			if (info.service.getClassName().equals(serviceName)) {
				return true;
			}
		}
		return false;
	}
}


